package com.qingchunlin.blogsystem.config;

import com.qingchunlin.blogsystem.common.utils.JWTUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Configuration
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //进行用户登录校验
        //1. 从header中获取token
        //2. 验证token
        String token = request.getHeader("user_token");
        if (!StringUtils.hasLength(token)) {
            //token不合法
            response.setStatus(401);
            return false;
        }

        log.info("从header中取出token: token{}", token);

        Claims claims = JWTUtils.parseJWTToken(token);
        if (claims == null) {
            //token不合法
            response.setStatus(401);
            return false;
        }
        return true;
    }
}
